using System;
using System.Data;
using Aluetjen.EmailService.Domain.Infrastructure;
using NHibernate;

namespace Aluetjen.EmailService.Infrastructure.Persistence
{
    public class NHibernateUnitOfWork : IUnitOfWork
    {
        private readonly ISessionFactory _sessionFactory;
        private ITransaction _transaction;
        private ISession _session;

        public ISession Session
        {
            get
            {
                if(_session == null)
                {
                    _session = _sessionFactory.OpenSession();
                    _session.FlushMode = FlushMode.Auto;
                    _transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted);
                }

                return _session;
            }
        }

        public NHibernateUnitOfWork(ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
        }

        public void Dispose()
        {
            if (_session != null)
            {
                _transaction.Dispose();
                _session.Dispose();
            }
        }

        public void Commit()
        {
            if (_session != null)
            {
                if (!_transaction.IsActive)
                {
                    throw new InvalidOperationException("No active transaction");
                }

                _transaction.Commit();
            }
        }

        public void Rollback()
        {
            if (_session != null)
            {
                if (_transaction.IsActive)
                {
                    _transaction.Rollback();
                }
            }
        }
    }
}